package com.shishuo.cms.action.manage;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.shishuo.cms.action.BaseAjaxAction;
import com.shishuo.cms.auth.AuthPassport;
import com.shishuo.cms.constant.SystemConstant;
import com.shishuo.cms.entity.Admin;
import com.shishuo.cms.entity.vo.JsonVo;
import com.shishuo.cms.exception.AuthException;
import com.shishuo.cms.exception.FolderNotFoundException;
import com.shishuo.cms.exception.ParameterException;
import com.shishuo.cms.service.AdminService;
import com.shishuo.cms.util.AuthUtils;

@Controller
@RequestMapping("/admin")
public class AdminIndexAction extends BaseAjaxAction{
	
	@Autowired
	private DefaultKaptcha captchaProducer;
	@Autowired
	private AdminService adminService;
	/*@RequestMapping 
	public void index(HttpServletResponse response) throws Exception {
		response.sendRedirect("/admin/");
	}*/
	@AuthPassport
	@RequestMapping(value ={ "/index.htm","/"}, method = RequestMethod.GET)
	public String index(ModelMap modelMap) throws Exception {
		return "system/index";
	}
	@RequestMapping(value ={"/login.htm"}, method = RequestMethod.GET)
	public String login(ModelMap modelMap) throws Exception {
		HttpSession session = request.getSession();
		if(null!=session.getAttribute(SystemConstant.SESSION_ADMIN)){
			response.sendRedirect("/admin/index.htm");
		}
		return "system/login";
	}
	@RequestMapping(value ={"/logout.htm"}, method = RequestMethod.GET)
	public String logout(ModelMap modelMap) throws Exception {
		HttpSession session = request.getSession();
		session.setAttribute(SystemConstant.SESSION_ADMIN, null);
		return "system/login";
	}
	@RequestMapping(value ={"/noAuth.htm"}, method = RequestMethod.GET)
	public String noAuth(ModelMap modelMap) throws Exception {
		return "system/noAuth";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/login.json", method = RequestMethod.POST)
	public JsonVo<String> loginJson(@RequestParam(value = "email") String email,
			@RequestParam(value = "password") String password,
			@RequestParam(value = "captcha") String captcha,ModelMap modelMap) throws Exception {
		JsonVo<String> json = new JsonVo<String>();
		try {
			String kaptcha = (String) request.getSession().getAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			if (!EmailValidator.getInstance().isValid(email)) {
				json.getErrors().put("email", "邮件格式错误");
			}
			if (StringUtils.isBlank(password)) {
				json.getErrors().put("password", "密码不能为空");
			} else if (password.length() < 6 && password.length() > 30) {
				json.getErrors().put("password", "密码最少6个字符，最多30个字符");
			}
			// 校验验证码
			if (StringUtils.isNotBlank(kaptcha)
					&& kaptcha.equalsIgnoreCase(captcha)) {

			} else {
				json.getErrors().put("captcha", "验证码错误");
			}
			this.validate(json);
			Admin admin = adminService.getAdminByEmail(email);
			if (admin == null) {
				throw new AuthException("邮箱或密码错误");
			}
			String loginPassword = AuthUtils.getPassword(password, email);
			if (loginPassword.equals(admin.getPassword())) {
				HttpSession session = request.getSession();
				admin.setPassword("");
				session.setAttribute(SystemConstant.SESSION_ADMIN, admin);
			} else {
				throw new AuthException("邮箱或密码错误");
			}
		} catch (Exception e) {
			// 异常，重置验证码
			request.getSession().removeAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			json.setResult(false);
			json.getErrors().put("password", "邮箱或密码错误");
			json.setMsg("change_captcha");
		}
		return json;
	}
	
	
	@RequestMapping(value = "captcha.htm", method = RequestMethod.GET)
	public void captcha(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		request.getSession().setAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
}
